# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 15:13:32 2019

@author: puhua
"""
import django
import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

'''
Django 版本大于等于1.7的时候，需要加上下面两句
import django
django.setup()
否则会抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
'''
if django.VERSION >= (1, 7):  # 自动判断版本
    django.setup()

'''
def main():
    from blog.models import Blog
    f = open('oldblog.txt', 'r')
    for line in f:
        title, content = line.split('****')
        Blog.objects.create(title=title, content=content)
    f.close()
'''


def main():
    from blog.models import Blog
    f = open('oldblog.txt')
    '''
    blog_list = [] 
    for line in f:
        title, content = line.split('****')
        blog = Blog(title=title, content=content)
        blog_list.append(blog)
    '''
    # 使用列表解析比for循环更快
    blog_list = [Blog(title=line.split('****')[0], content=line.split('****')[1]) for line in f]
    f.close()

    # bulk_create()执行一条SQL语句存入多条数据，执行效率更高
    Blog.objects.bulk_create(blog_list)


if __name__ == "__main__":
    main()
    print('Done!')
